package io.renren.controller;


import com.google.common.base.Preconditions;
import io.renren.annotation.Login;
import io.renren.annotation.SysLog;
import io.renren.common.utils.R;
import io.renren.common.utils.UUIDUtils;
import io.renren.config.GlobalConfig;
import io.renren.entity.UserEntity;
import io.renren.service.UserService;
import io.renren.util.FileResult;
import io.renren.util.FileuploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
@Api(tags = "文件上传")
public class ApiImageUploadController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApiImageUploadController.class);

    @Autowired
    GlobalConfig globalConfig;

    @Autowired
    UserService userService;


    @Login
    @PostMapping("/user/updateProfile_bak")
    @ApiOperation("上传用户头像")
    public R upload_bak(@RequestParam("picture") MultipartFile picture, @RequestAttribute("userId") String userId, HttpServletRequest request) {
        //获取文件在服务器的储存位置
        String path = request.getSession().getServletContext().getRealPath("/upload");
        File filePath = new File(path);
        System.out.println("文件的保存路径：" + path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            System.out.println("目录不存在，创建目录:" + filePath);
            filePath.mkdir();
        }

        //获取原始文件名称(包含格式)
        String originalFileName = picture.getOriginalFilename();
        //获取文件类型，以最后一个`.`为标识
        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        //获取文件名称（不包含格式）
        String uuidName = UUIDUtils.getUUID();

        //设置文件新名称: 当前时间+文件名称（不包含格式）
        Date d = new Date();
        String fileName = uuidName + "." + type;
        //在指定路径下创建一个文件
        File targetFile = new File(path, fileName);
        //将文件保存到服务器指定位置
        try {
            picture.transferTo(targetFile);
            //将文件在服务器的存储路径返回
            Map<String, Object> queryResult = new HashMap<>();
            System.out.println(globalConfig.getImageHost());

            // 更新db

            userService.upldateUserPortait(userId, globalConfig.getImageHost() + "/upload/" + fileName);

            queryResult.put("imageUrl", "/upload/" + fileName);
            return R.ok(queryResult);
        } catch (IOException e) {
            LOGGER.info("上传头像失败:" + e.toString());
            return R.error("上传失败");
        }
    }


    @Login
    @PostMapping("/user/updateProfile")
    @SysLog("用户上传头像")
    @ApiOperation("上传用户头像")
    public R uploadProfile(@RequestParam("picture") MultipartFile picture, @RequestAttribute("userId") String userId, HttpServletRequest request) {
        Map<String, Object> queryResult = new HashMap<>();
        try {
            FileResult fileResult = FileuploadUtil.saveImage(picture, "", "");
            String userProfilePath = globalConfig.getImageHost() + fileResult.getServerPath();
            queryResult.put("imageUrl", userProfilePath);
            // 更新db
            userService.upldateUserPortait(userId, userProfilePath);
            return R.ok(queryResult);
        } catch (IOException e) {
            LOGGER.info("上传头像失败:" + e.toString());
            return R.error("上传失败");
        }
    }


    @SysLog("用户上传文件")
    @ApiOperation(value = "文件上传", notes = "图片也可以使用，但是图片不会被压缩")
    @PostMapping("/uploadFile")
    public R uploadFile(
            MultipartFile picture,
            @RequestParam(value = "childFile", required = false, defaultValue = "") String childFile,
            @RequestParam(value = "extension", required = false, defaultValue = "") String extension
    ) throws IOException {
        Map<String, Object> queryResult = new HashMap<>();
        queryResult.put("imageUrl", FileuploadUtil.saveFile(picture, childFile, extension));
        return R.ok(queryResult);
    }


    /**
     * 方法描述：图片上传，只能给图片使用，其他文件调用会异常.
     * 创建时间：2018-10-19 14:10:32
     *
     * @param childFile 上传的父目录
     * @param extension 允许上传的文件后缀名
     * @author "lixingwu"
     */
    @SysLog("用户上传图片")
    @ApiOperation(value = "图片上传", notes = "只能给图片使用，其他文件调用会异常")
    @PostMapping("/image/upload")
    public R uploadImage(
            MultipartFile picture,
            @RequestParam(value = "childFile", required = false, defaultValue = "") String childFile,
            @RequestParam(value = "extension", required = false, defaultValue = "") String extension
    ) throws IOException {
        Map<String, Object> queryResult = new HashMap<>();

        FileResult fileResult = FileuploadUtil.saveImage(picture, childFile, extension);
        queryResult.put("imageUrl", globalConfig.getImageHost() + fileResult.getServerPath());
        return R.ok(queryResult);
    }


    /**
     * IO流读取图片 by:long
     *
     * @return
     */
    @RequestMapping(value = "/image/show/{userId}", method = RequestMethod.GET)
    public String IoReadImage(@PathVariable String userId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletOutputStream out = null;
        InputStream ips = null;
        String imgPath = null;
        try {
            //获取图片存放路径
            UserEntity userEntity = userService.selectById(userId);
//            String imgPath = Constans.FOLDER_IMAGE + imgName;
            imgPath = userEntity.getAvatar();
            ips = this.getImageStream(imgPath);
            Preconditions.checkArgument(null != ips, "下载头像失败");
            response.setContentType("multipart/form-data");
            out = response.getOutputStream();
            //读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = ips.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("download image error: {}, {}", imgPath, e.toString());
        } finally {
            out.close();
            ips.close();
        }
        return null;
    }


    /**
     * 获取网络图片流
     *
     * @param url
     * @return
     */
    public InputStream getImageStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常，图片路径为：" + url);
            e.printStackTrace();
        }
        return null;
    }


}
